# 恢复环境
from libs import northstar
from time import *
import sys
def start_webrepl(): # 启动webrepl
    northstar.oled.fill(1)
    northstar.oled.show()
    print("webrepl is start")
    sleep(2)
    if ("webrepl.cfg" not in os.listdir("config")) or (northstar.button.get('A')):
        while northstar.button.get('A'): pass
        wpwd=northstar.screen.input_text("set webrepl passwd:")
        with open("config/webrepl.cfg","w") as file:
            file.write(wpwd)
        northstar.oled.fill(1)
        northstar.oled.show()
    with open("config/webrepl.cfg") as file:
        wpwd=file.read()
    import webrepl
    webrepl.start(port=5555,password=wpwd)
    sleep(2)
    northstar.oled.fill(0)
    northstar.oled.text("WebREPL mode",0,0)
    northstar.oled.text("ip:",0,12)
    northstar.oled.text("ws://"+northstar.wifi.ifconfig()[0]+":",0,24)
    northstar.oled.text("5555",80,36)
    northstar.oled.show()
    import sys
    sys.exit()

import os
northstar.init_BUTTON()
if northstar.button.get('A')==1: # 进入菜单
    if northstar.button.get('B')==1:
        sys.exit(0)
    northstar.init_SCREEN()
    menulist=[
        "run system",          # 启动系统
        "wifi              >", # 网络功能
        ["tools",              # 内置工具
            ["test button"]    # 测试按钮
        ],
        ["programs",           # 外置程序
            ["no data"]
        ],
        "reboot"
    ]
    while northstar.button.get('A'): pass
    getmenu = northstar.screen.show_list(menulist)
    if getmenu[0]==0: # 启动系统
        import main
    elif getmenu[0]==1: # 网络模式
        menulist=[
            "start webrepl",
            "run wsc mode"
        ]
        northstar.init_NETWORK()
        print(northstar.networks.connect_menu())
        getmenu = northstar.screen.show_list(menulist)
        if getmenu[0]==0:
            start_webrepl()
        elif getmenu[0]==1:
            from system_app import wsc
    elif getmenu[0]==2: # tools
        if getmenu[1]==0: # 测试按钮
            from system_app import test_btn
        elif getmenu[1]==1: # 联网并启动
            connect_wifi()
            import main
    elif getmenu[0]==3:
        pass
    elif getmenu[0]==4:
        if northstar.button.get('B')==0: # 软重启
            print("soft reboot")
            import sys
            sys.exit()
        else: # machine硬重启
            print("reboot")
            import machine
            machine.reset()

    
    